package com.dwxt.sport.business.service;

import com.dwxt.common.base.StatusCode;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.SnowIdUtil;
import com.dwxt.sport.business.dao.AdolescentSportsHealthEquipmentMapper;
import com.dwxt.sport.business.dao.AdolescentSportsHealthMapper;
import com.dwxt.sport.business.entity.AdolescentSportsHealth;
import com.dwxt.sport.business.entity.AdolescentSportsHealthEquipment;
import com.dwxt.sport.business.vo.adolescentSportsHealth.InsertOrUpdateAdolescentSportsHealthEquipmentVo;
import com.dwxt.sport.business.vo.adolescentSportsHealth.InsertOrUpdateAdolescentSportsHealthVo;
import com.dwxt.sport.business.vo.adolescentSportsHealth.SelectAdolescentSportsHealthVo;
import com.dwxt.sport.constant.CommonConstant;
import com.dwxt.sport.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 青少年运动健康
 *
 * @author Kuang.JiaZhuo
 * @date 2020-07-30 10:16
 */
@Service
public class AdolescentSportsHealthService {

    @Resource
    AdolescentSportsHealthMapper adolescentSportsHealthMapper;

    @Resource
    AdolescentSportsHealthEquipmentMapper healthEquipmentMapper;

    /**
     * @方法名：insertOrUpdateAdolescentSportsHealth
     * @描述： 新增或修改青少年运动健康
     * @作者： kjz
     * @日期： Created in 2020/7/30 10:27
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOrUpdateAdolescentSportsHealth(InsertOrUpdateAdolescentSportsHealthVo insertOrUpdateVo) {

        String id = insertOrUpdateVo.getId();

        AdolescentSportsHealth adolescentSportsHealth = new AdolescentSportsHealth()
                .setName(insertOrUpdateVo.getName()) //设备名称
                .setEquipmentsImgUrl(insertOrUpdateVo.getEquipmentsImgUrl()) //设备图片地址
                .setRecommendedCoverage(insertOrUpdateVo.getRecommendedCoverage()); //建议覆盖率
        if(null==id || id.trim().length()==0){
            //新增
            adolescentSportsHealth.setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now()).setIsDelete(VariableConstants.STRING_CONSTANT_0)
                    .setStreetId(insertOrUpdateVo.getStreetId()); //街道id
            return adolescentSportsHealthMapper.insert(adolescentSportsHealth);
        }else{
            //更新
            adolescentSportsHealth.setUpdateTime(LocalDateTime.now()).setId(id);
            return adolescentSportsHealthMapper.updateByPrimaryKeySelective(adolescentSportsHealth);
        }

    }

    /**
     * @方法名：selectAdolescentSportsHealthByCriteria
     * @描述： 获取青少年运动健康列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/30 11:15
     */
    public PageInfo<AdolescentSportsHealth> selectAdolescentSportsHealthByCriteria(SelectAdolescentSportsHealthVo selectVo) {
        PageHelper.startPage(selectVo.getPageNum(), selectVo.getPageSize());
        List<AdolescentSportsHealth> list = adolescentSportsHealthMapper.selectAdolescentSportsHealthByCriteria(selectVo);
        list.forEach(adolescentSportsHealth -> {
            adolescentSportsHealth.setEquipmentsImgUrl(CommonConstant.FILE_SERVER+adolescentSportsHealth.getEquipmentsImgUrl());
        });
        PageInfo<AdolescentSportsHealth> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * @方法名：deleteAdolescentSportsHealthByIds
     * @描述： 根据ids批量删除【青少年运动健康】
     * @作者： kjz
     * @日期： Created in 2020/7/30 11:56
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteAdolescentSportsHealthByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        String[] idArray = ids.split(",");

        return this.adolescentSportsHealthMapper.deleteAdolescentSportsHealthByIds(idArray);
    }


    /*************************************** 关联设备 *********************************************************/

    /**
     * @方法名：insertOrUpdateAdolescentSportsHealthEquipment
     * @描述： 新增 或 更新【青少年运动健康】设备关联
     * @作者： kjz
     * @日期： Created in 2020/7/30 13:18
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOrUpdateAdolescentSportsHealthEquipment(InsertOrUpdateAdolescentSportsHealthEquipmentVo insertOrUpdateVo) {
        String id = insertOrUpdateVo.getId();

        AdolescentSportsHealthEquipment healthEquipment = new AdolescentSportsHealthEquipment()
                .setEquipmentId(insertOrUpdateVo.getEquipmentId()) //设备id
                .setCumulativePerson(insertOrUpdateVo.getCumulativePerson()) //累计人次
                .setAvg(insertOrUpdateVo.getAveragePeople()) //平均人次
                .setTodayPeople(insertOrUpdateVo.getTodayPeople()) //今日人次
                .setTotalUsageTime(insertOrUpdateVo.getTotalUsageTime()) //使用总时长(单位:min)
                .setRemark(insertOrUpdateVo.getRemark()) //备注
                .setDeviceStates(insertOrUpdateVo.getDeviceStates()); //设备状态

        String healthId = insertOrUpdateVo.getHealthId();
        int result = 0;
        if (null == id || id.trim().length() == 0) {
            //新增
            if (null == healthId || healthId.trim().length() == 0) {
                throw new CustomException(StatusCode.HEALTH_ID_IS_NULL);
            }
            healthEquipment.setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now()).setIsDelete(VariableConstants.STRING_CONSTANT_0)
                    .setHealthId(insertOrUpdateVo.getHealthId()); //青少年运动健康关联id
            result = healthEquipmentMapper.insert(healthEquipment);

        } else {
            //更新
            healthEquipment.setUpdateTime(LocalDateTime.now()).setId(id);
            result = healthEquipmentMapper.updateByPrimaryKeySelective(healthEquipment);
        }


        if(result>0){
            this.updateAdolescentSportsHealth(healthId);
        }
        
        return result;
    }

    /**
     * @方法名：updateAdolescentSportsHealth
     * @描述： 新增或更新关联设备成功后更新青少年运动健康需要计算的数据
     * @作者： kjz
     * @日期： Created in 2020/8/4 14:35
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateAdolescentSportsHealth(String healthId) {
        HashMap map = healthEquipmentMapper.selectStatisticsByHealthId(healthId);
        AdolescentSportsHealth adolescentSportsHealth = new AdolescentSportsHealth()
                .setAmount(Integer.valueOf(map.get("amount").toString()))
                .setTotalPersonTimes(Integer.valueOf(map.get("totalPersonTimes").toString()))
                .setAvg(Double.parseDouble(map.get("avgElapsedTime").toString()))
                .setUpdateTime(LocalDateTime.now())
                .setId(healthId);
       return adolescentSportsHealthMapper.updateByPrimaryKeySelective(adolescentSportsHealth);
    }

    /**
     * @方法名：deleteAdolescentSportsHealthEquipmentByIds
     * @描述： 根据ids批量删除【青少年运动健康】设备关联
     * @作者： kjz
     * @日期： Created in 2020/7/30 13:33
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteAdolescentSportsHealthEquipmentByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        String[] idArray = ids.split(",");

        int result = this.healthEquipmentMapper.deleteAdolescentSportsHealthEquipmentByIds(idArray);

        if(result>0){
            String id = idArray[0];
            String healthId = this.healthEquipmentMapper.selectByPrimaryKey(id).getHealthId();
            this.updateAdolescentSportsHealth(healthId);
        }

        return result;
    }

    /**
     * @方法名：selectAdolescentSportsHealthEquipmentByCriteria
     * @描述： 根据【青少年运动健康】的id查询关联设备的列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/30 13:40
     */
    public PageInfo<AdolescentSportsHealthEquipment> selectAdolescentSportsHealthEquipmentByCriteria(Integer pageNum, Integer pageSize, String healthId) {
        PageHelper.startPage(pageNum==null?1:pageNum, pageSize==null?10:pageSize);
        List<AdolescentSportsHealthEquipment> list = healthEquipmentMapper.selectAdolescentSportsHealthEquipmentByCriteria(healthId);
        PageInfo<AdolescentSportsHealthEquipment> pageInfo = new PageInfo(list);
        return pageInfo;
    }
}
